package com.ysstech.reportworld.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ysstech.common.cache.RedisCacheManager;
import com.ysstech.common.entity.PageBean;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.service.DicvalueService;
import com.ysstech.common.util.DateUtil;
import com.ysstech.reportworld.entity.*;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.mapper.DataSqlMapper;
import com.ysstech.reportworld.service.DataCustomerService;
import com.ysstech.reportworld.service.DataModularService;
import com.ysstech.reportworld.service.DataReportService;
import com.ysstech.reportworld.service.DataSqlService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 报表世界函数信息表 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2022-05-19
 */
@Service
@Slf4j
public class DataSqlServiceImpl extends ServiceImpl<DataSqlMapper, DataSql> implements DataSqlService {

    @Autowired
    private DicvalueService dicvalueService;
    @Autowired
    private DataSqlMapper dataSqlMapper;
    @Autowired
    private DataCustomerService dataCustomerService;
    @Autowired
    private DataModularService dataModularService;
    @Autowired
    private DataReportService dataReportService;
    @Autowired
    private RedisCacheManager redisCacheManager;

    public List<DataSql> queryAllDataSqls(DataSql dataSql) throws Exception {
        DataSql dataSqlNew = getQueryWrapper(dataSql);
        return this.switchedListDataSql(dataSqlMapper.queryReportDataSql(dataSqlNew));
    }

    /**
     * 获取函数信息
     *
     * @param dataSql
     * @param pageBean
     * @return
     * @throws Exception
     */
    public PageBean<DataSql> queryAllDataSqls(DataSql dataSql, PageBean pageBean) throws Exception {
        // QueryWrapper<DataSql> wrapper = this.getQueryWrapper(dataSql);
        DataSql dataSqlNew = getQueryWrapper(dataSql);
        IPage pageScheduleLog = dataSqlMapper.queryReportDataSql(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), dataSqlNew);
        this.switchedListDataSql(pageScheduleLog.getRecords());
        return new PageBean<>(pageScheduleLog);
    }

    /**
     * 处理查询条件信息
     *
     * @param dataSql
     * @return
     */
    private DataSql getQueryWrapper(DataSql dataSql) {
        if (null == dataSql) {
            return null;
        }
        if (StringUtils.isNotBlank(dataSql.getStrReport())) {
            List<String> ids = JSONArray.parseArray(dataSql.getStrReport(), String.class);
            List<DataReport> list = new ArrayList<>();
            for (String str : ids) {
                DataReport dataReport = new DataReport();
                dataReport.setReportId(str);
                dataReport.setDataCode(ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
                list.add(dataReport);
            }
            dataSql.setListReport(list);
        }
        if (StringUtils.isNotBlank(dataSql.getStrCustomer())) {
            List<String> ids = JSONArray.parseArray(dataSql.getStrCustomer(), String.class);
            List<DataCustomer> list = new ArrayList<>();
            for (String str : ids) {
                DataCustomer dataCustomer = new DataCustomer();
                dataCustomer.setCustomerId(str);
                dataCustomer.setDataCode(ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
                list.add(dataCustomer);
            }
            dataSql.setListCustomer(list);
        }
        if (StringUtils.isNotBlank(dataSql.getStrModular())) {
            List<String> ids = JSONArray.parseArray(dataSql.getStrModular(), String.class);
            List<DataModular> list = new ArrayList<>();
            for (String str : ids) {
                DataModular dataModular = new DataModular();
                dataModular.setModularId(str);
                dataModular.setDataCode(ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
                list.add(dataModular);
            }
            dataSql.setListModular(list);
        }
        if (StringUtils.isNotBlank(dataSql.getName())) {
            dataSql.setName(dataSql.getName().toUpperCase());
        }
        return dataSql;
    }

    /**
     * 类型，机构等中文的转换
     *
     * @param list
     * @return
     * @throws Exception
     */
    private List<DataSql> switchedListDataSql(List<DataSql> list) throws Exception {
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        Map<String, String> mapType = dicvalueService.getCacheDicValueMap(ReportWorldEnum.DATASQL.getCode());
        //状态
        Map<String, String> mapStatus = dicvalueService.getCacheDicValueMap(ReportWorldEnum.REPORT_STATUS.getCode());
        for (DataSql dataSql : list) {
            if (null == dataSql) {
                continue;
            }
            if (null != mapType && mapType.containsKey(String.valueOf(dataSql.getType()))) {
                dataSql.setStrType(mapType.get(String.valueOf(dataSql.getType())));
            }
            //状态
            if (null != mapStatus && mapStatus.containsKey(String.valueOf(dataSql.getStatus()))) {
                dataSql.setStrStatus(mapStatus.get(String.valueOf(dataSql.getStatus())));
            }
            // 所属模块
            dataSql.setModular("");
            if (!CollectionUtils.isEmpty(dataSql.getListModular())) {
                StringBuffer modularId = new StringBuffer();
                StringBuffer modularName = new StringBuffer();
                for (DataModular reportTableModular : dataSql.getListModular()) {
                    modularId.append(reportTableModular.getModularId()).append(",");
                    modularName.append(reportTableModular.getModularName()).append("/");
                }
                dataSql.setStrModular(modularName.deleteCharAt(modularName.length() - 1).toString());
                dataSql.setModular(modularId.deleteCharAt(modularId.length() - 1).toString());
            }
            // 所属客户
            dataSql.setCustomer("");
            if (!CollectionUtils.isEmpty(dataSql.getListCustomer())) {
                StringBuffer customeId = new StringBuffer();
                StringBuffer customeName = new StringBuffer();
                for (DataCustomer reportTableCustomer : dataSql.getListCustomer()) {
                    customeId.append(reportTableCustomer.getCustomerId()).append(",");
                    customeName.append(reportTableCustomer.getCustomerName()).append("/");
                }
                dataSql.setStrCustomer(customeName.deleteCharAt(customeName.length() - 1).toString());
                dataSql.setCustomer(customeId.deleteCharAt(customeId.length() - 1).toString());
            }
            // 所属报表
            dataSql.setReport("");
            if (!CollectionUtils.isEmpty(dataSql.getListReport())) {
                StringBuffer reportId = new StringBuffer();
                StringBuffer reportName = new StringBuffer();
                for (DataReport reportTableReport : dataSql.getListReport()) {
                    reportId.append(reportTableReport.getReportId()).append(",");
                    reportName.append(reportTableReport.getReportName()).append("/");
                }
                dataSql.setStrReport(reportName.deleteCharAt(reportName.length() - 1).toString());
                dataSql.setReport(reportId.deleteCharAt(reportId.length() - 1).toString());
            }
        }
        return list;
    }


    /**
     * 新增SQL信息
     *
     * @param dataSql
     * @throws Exception
     */
    @Transactional
    public void addReportDataSql(DataSql dataSql) throws Exception {
        if (null == dataSql) {
            throw new BusinessException("获取删除报表世界表结构信息失败，请稍后重试！");
        }
        if (StringUtils.isNotBlank(dataSql.getName())) {
            dataSql.setName(dataSql.getName().toUpperCase());
        }
        dataSql.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
        dataSql.setId(DateUtil.generateUUID());
        dataSql.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
        dataSql.setAddTime(LocalDateTime.now());
        this.addDataSqlInfo(dataSql);
        this.save(dataSql);
    }

    /**
     * 保存SQL关联关系信息
     *
     * @param dataSql
     * @throws Exception
     */
    private void addDataSqlInfo(DataSql dataSql) throws Exception {
        if (StringUtils.isNotBlank(dataSql.getStrCustomer())) {
            List<String> ids = JSONArray.parseArray(dataSql.getStrCustomer(), String.class);
            List<DataCustomer> list = new ArrayList<>();
            for (String str : ids) {
                DataCustomer dataCustomer = new DataCustomer();
                dataCustomer.setId(DateUtil.generateUUID());
                dataCustomer.setCustomerId(str);
                dataCustomer.setDataId(dataSql.getId());
                dataCustomer.setDataCode(ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
                list.add(dataCustomer);
            }
            dataCustomerService.saveBatch(list);
        }
        if (StringUtils.isNotBlank(dataSql.getStrModular())) {
            List<String> ids = JSONArray.parseArray(dataSql.getStrModular(), String.class);
            List<DataModular> list = new ArrayList<>();
            for (String str : ids) {
                DataModular dataModular = new DataModular();
                dataModular.setId(DateUtil.generateUUID());
                dataModular.setModularId(str);
                dataModular.setDataId(dataSql.getId());
                dataModular.setDataCode(ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
                list.add(dataModular);
            }
            dataModularService.saveBatch(list);
        }
        if (StringUtils.isNotBlank(dataSql.getStrReport())) {
            List<String> ids = JSONArray.parseArray(dataSql.getStrReport(), String.class);
            List<DataReport> list = new ArrayList<>();
            for (String str : ids) {
                DataReport dataReport = new DataReport();
                dataReport.setId(DateUtil.generateUUID());
                dataReport.setReportId(str);
                dataReport.setDataId(dataSql.getId());
                dataReport.setDataCode(ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
                list.add(dataReport);
            }
            dataReportService.saveBatch(list);
        }
    }

    /**
     * 修改SQL信息 ,同步修改表字段得所属科目，模块，报表信息
     *
     * @param dataSql
     * @throws Exception
     */
    @Transactional
    public void updateReportDataSql(DataSql dataSql) throws Exception {
        if (null == dataSql) {
            throw new BusinessException("获取删除报表世界表结构信息失败，请稍后重试！");
        }
        if (StringUtils.isNotBlank(dataSql.getName())) {
            dataSql.setName(dataSql.getName().toUpperCase());
        }
        dataSql.setEditTime(LocalDateTime.now());
        // 修改表信息
        this.updateById(dataSql);

        //删除表和客户信息关联关系
        QueryWrapper<DataCustomer> wrapperCustomer = new QueryWrapper<>();
        wrapperCustomer.in("DATA_ID", dataSql.getId());
        wrapperCustomer.eq("DATA_CODE", ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
        dataCustomerService.remove(wrapperCustomer);
        //删除表和模块信息关联关系
        QueryWrapper<DataModular> wrapperModular = new QueryWrapper<>();
        wrapperModular.in("DATA_ID", dataSql.getId());
        wrapperModular.eq("DATA_CODE", ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
        dataModularService.remove(wrapperModular);
        //删除表和报表信息关联关系
        QueryWrapper<DataReport> wrapperReport = new QueryWrapper<>();
        wrapperReport.in("DATA_ID", dataSql.getId());
        wrapperReport.eq("DATA_CODE", ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
        dataReportService.remove(wrapperReport);
        // 保存对应关系信息
        this.addDataSqlInfo(dataSql);
    }

    /**
     * 删除SQL信息
     *
     * @param id
     * @throws Exception
     */
    @Transactional
    public void deleteReportDataSql(String id) throws Exception {
        if (StringUtils.isBlank(id)) {
            throw new BusinessException("获取删除报表世界表结构信息失败，请稍后重试！");
        }
        List<String> ids = JSONArray.parseArray(id, String.class);
        this.removeByIds(ids);
        //删除SQL和客户信息关联关系
        QueryWrapper<DataCustomer> wrapperCustomer = new QueryWrapper<>();
        wrapperCustomer.in("DATA_ID", ids);
        wrapperCustomer.eq("DATA_CODE", ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
        dataCustomerService.remove(wrapperCustomer);
        //删除SQL和模块信息关联关系
        QueryWrapper<DataModular> wrapperModular = new QueryWrapper<>();
        wrapperModular.in("DATA_ID", ids);
        wrapperModular.eq("DATA_CODE", ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
        dataModularService.remove(wrapperModular);
        //删除表SQL和报表信息关联关系
        QueryWrapper<DataReport> wrapperReport = new QueryWrapper<>();
        wrapperReport.in("DATA_ID", ids);
        wrapperReport.eq("DATA_CODE", ReportWorldEnum.REPORT_DATASQL_CODE.getCode());
        dataReportService.remove(wrapperReport);
    }
}
